# 上传api
import json

from django.shortcuts import HttpResponse

from web.models import images

from django import forms


class st_images(forms.ModelForm):
    class Meta:
        model = images
        fields = '__all__'


def store_images(request):
    if request.method == 'POST':
        data = request.POST.dict()
        form = st_images(data=data)
        if form.is_valid():
            upres = images.objects.filter(title=data['title'], image_type=data['image_type'],
                                          image_id=data['image_id']).first()
            if upres:
                return HttpResponse("上传失败,当前已有相同的商家封面",status=500)
            images.objects.create(title=data['title'], image_type=data['image_type'],image_id=data['image_id'],image_url= request.FILES['image_url'])
            upres = images.objects.filter(title=data['title'], image_type=data['image_type'],image_id=data['image_id']).first()
            result = {
                "src": str(upres.image_url),
                "data": "上传成功"
            }
            return HttpResponse(json.dumps(result))
        else:
            print(form.errors)
            return HttpResponse("--upFileError--", status=400)
